//
//  BCString.swift
//  BCProject
//
//  Created by you&me on 2017/11/22.
//  Copyright © 2017年 杨杨威. All rights reserved.
//

import Foundation

extension String {
    func trim() -> String {
        return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    }
    
    //MARK: -  正则表达式验证
    public enum ValidatedType: String {
        case Email = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
        case PhoneNumber = "^1[0-9]{10}$"
    }
    
    /**
     正则验证
     - parameter type: 验证类型
     - returns:验证结果
     */
    func validateText(_ validatedType: ValidatedType) -> Bool {
        do {
            let pattern = validatedType.rawValue
            let regex: NSRegularExpression = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            let matches = regex.matches(in: self, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, self.count))
            return matches.count > 0
        }
        catch {
            return false
        }
    }
    
    /**
     根据时长格式化输出
     - parameter duration: 单位(秒)
     
     - returns: 返回格式化后的时长
     */
    func getFormatterDuration(_ duration: Int) -> String {
        let hour = duration / 3600
        let minute = (duration - hour * 3600) / 60
        if hour <= 0 {
            return "\(minute)分钟"
        }
        if minute <= 0 {
            return "\(hour)小时"
        }
        return "\(hour)小时\(minute)分钟"
    }
    
    /**
     根据正则过滤公交线路名称(例子:949路(厦门北站--前埔公交场站) -> 949路)
     - returns: 过滤后的名称
     */
    func getSimpleSimpleBusLineName() -> String {
        let pattern = "\\(.*?\\)"
        let regular = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
        let string = regular.stringByReplacingMatches(in: self, options: .reportCompletion, range: NSMakeRange(0, self.characters.count), withTemplate: "")
        return string
    }
    
    /// 获取本地化字符串
    ///
    /// - Returns: 本地化字符串
    func localized() -> String {
        return NSLocalizedString(self, comment: self)
    }

}
